package org.shean.app.rssreader;

import org.shean.app.rssreader.provider.SzRSSReader;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RenameChannelAcvtivity extends Activity {
	private EditText mChannelTitle;
	private Button mSaveButton;
	private long mRenameId = -1;
	private String mOriginalName;
	
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.rename_channel_title);
        getWindow().setLayout(WindowManager.LayoutParams.FILL_PARENT,
                                    WindowManager.LayoutParams.WRAP_CONTENT);

        mChannelTitle = (EditText)findViewById(R.id.channel_title);
        
        mSaveButton = (Button) findViewById(R.id.rename);
        mSaveButton.setOnClickListener(mOpenClicked);

        ((Button)findViewById(R.id.cancel)).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });
        
        mRenameId = icicle != null ? icicle.getLong("rename")
                : getIntent().getLongExtra("rename", -1);
        
        Cursor ret = null;

		String[] cols = new String[] { SzRSSReader.Channels._ID, SzRSSReader.Channels.TITLE };
		ret = managedQuery(ContentUris.withAppendedId(SzRSSReader.Channels.CONTENT_URI, mRenameId), cols, null,
				null, null);
		ret.moveToFirst();
        mOriginalName = ret.getString(ret.getColumnIndexOrThrow(SzRSSReader.Channels.TITLE));
        ret.close();
        
        String defaultname = icicle != null ? icicle.getString("defaultname") : mOriginalName;
        
        mChannelTitle.setText(defaultname);
    }
    
    @Override
    public void onSaveInstanceState(Bundle outcicle) {
        outcicle.putString("defaultname", mChannelTitle.getText().toString());
        outcicle.putLong("rename", mRenameId);
    }
    
    private View.OnClickListener mOpenClicked = new View.OnClickListener() {
        public void onClick(View v) {
        	String name = mChannelTitle.getText().toString();
			if (name != null && name.length() > 0)
			{
				if(name.equals(mOriginalName))
				{
					finish();
				}
				else
				{
					Uri update = Uri.parse("content://" + SzRSSReader.AUTHORITY
							+ "/channels/" + mRenameId);
					ContentValues values = new ContentValues();
					values.put(SzRSSReader.Channels.TITLE, name);
					getContentResolver().update(update, values, null, null);
					
					setResult(RESULT_OK);
					finish();
				}
			}
        }
    };
    
}
